package com.mt.mtbletools;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.mt.help.GlobalVariable;
import com.mt.model.WXCfgModel;
import com.mt.mtbletools.R;
import com.mt.net.HTTPURL;
import com.mt.net.RequestWithToken.GetTokenCallback;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.model.ErroCode;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MTWXCfgActivity extends Activity {
	private GlobalVariable mGlobalVariable;
	private Handler handl = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mtwxcfg);
		mGlobalVariable = GlobalVariable.getinstance();

		getDefaultDatas();

		initView();
	}

	// 获取传送过来的数据
	private MTBLEDevice device;
	private int index;
	private String wxmac = "";

	private void getDefaultDatas() {
		index = getIntent().getIntExtra(ScanFragment.SELECTDEVICE, -1);
		if (index == -1) {
			finish();
			return;
		}
		if (mGlobalVariable.getDeviceList().size() == 0) {
			finish();
			return;
		}
		device = mGlobalVariable.getDeviceList().get(index);

		String mac = device.getDevice().getAddress();
		wxmac = mac.replace(":", "");
	}

	// 初始化控件
	private CheckBox crypt_check;
	private EditText cryptkey_edit;
	private CheckBox connectoutapp_check;
	private Button register_btn;
	private ProgressDialog pd;

	private void initView() {
		crypt_check = (CheckBox) findViewById(R.id.crypt_check);
		cryptkey_edit = (EditText) findViewById(R.id.cryptkey_edit);
		connectoutapp_check = (CheckBox) findViewById(R.id.connectoutapp_check);
		register_btn = (Button) findViewById(R.id.register_btn);

		register_btn.setOnClickListener(myOnClickListener);
	}

	// 按钮监听
	private OnClickListener myOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			pd = ProgressDialog.show(MTWXCfgActivity.this, "wait", "正在注册", true, true);
			try {
				WXCfgModel wxmodel = mGlobalVariable.getDb().selector(WXCfgModel.class).where("mac", "=", wxmac)
						.findFirst();

				if (wxmodel == null) {
					requestNewDevice();
				} else {
					reflashInf(wxmodel.getDeviceid());
				}
			} catch (DbException e) {
				e.printStackTrace();
			}
		}
	};

	// https://api.weixin.qq.com/device/getqrcode?access_token=CgKL__h4QbQL3DLL2uhlZ6ACgVAHZn1GMuLyqnJlWBEH2wPwWbrh_FvIPmlKTI81NC11bclsmoyUqibcEg4G7zIhl64ZhMP_pNWw5_GMKUvw_Gn5E8AyFPyvFQcC97iTPFQcAEACSD&product_id=8260
	// 申请新ID
	private void requestNewDevice() {
		System.out.println("requestNewDevice");
		if (pd.isShowing()) {
			pd.setMessage("申请新设备");
		}
		mGlobalVariable.getmRequestWithToken().gettoken(new GetTokenCallback() {

			@Override
			public void onGetOK(final String token, final int timeout) {
				StringRequest loginrequest = new StringRequest(Request.Method.POST, HTTPURL.REQUESTNEWDEVICE_URL,
						new Response.Listener<String>() {
					@Override
					public void onResponse(final String str) {
						System.out.println("requestNewDevice->" + str);
						try {
							JSONObject jsobj = new JSONObject(str);
							JSONObject base_resp = jsobj.getJSONObject("base_resp");
							if (base_resp.getInt("errcode") != 0) {
								final String erromsg = base_resp.getString("errmsg");
								handl.post(new Runnable() {

									@Override
									public void run() {
										if (pd.isShowing()) {
											Toast.makeText(getApplicationContext(), "申请新设备错误->" + erromsg,
													Toast.LENGTH_LONG).show();
											pd.dismiss();
										}
									}
								});
								System.out.println("获取错误->" + base_resp.getString("errmsg"));
								return;
							}
							String deviceid = jsobj.getString("deviceid");

							WXCfgModel wxmodel = new WXCfgModel();
							wxmodel.setDeviceid(deviceid);
							wxmodel.setMac(wxmac);

							try {
								mGlobalVariable.getDb().saveOrUpdate(wxmodel);
							} catch (DbException e) {
								e.printStackTrace();
							}

							reflashInf(deviceid);
						} catch (JSONException e) {
							e.printStackTrace();
							System.out.println("解析json错误->" + e.toString());
							return;
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(final VolleyError error) {
						handl.post(new Runnable() {

							@Override
							public void run() {
								if (pd.isShowing()) {
									Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
									pd.dismiss();
								}
							}
						});
					}
				}) {
					@Override
					protected Map<String, String> getParams() throws AuthFailureError {
						Map<String, String> usermap = new HashMap<String, String>();
						usermap.put("access_token", token);
						usermap.put("product_id", mGlobalVariable.getMixedvalues().getProductid());
						return usermap;
					}
				};
				mGlobalVariable.getmRequestWithToken().addRequest(loginrequest);
			}

			@Override
			public void onGetFail(ErroCode erro) {
				handl.post(new Runnable() {

					@Override
					public void run() {
						if (pd.isShowing()) {
							Toast.makeText(getApplicationContext(), "账号或者密码不对", Toast.LENGTH_LONG).show();
							pd.dismiss();
						}
					}
				});
			}

		});
	}

	// 更新设备信息
	private void reflashInf(final String deviceid) {

		handl.post(new Runnable() {

			@Override
			public void run() {
				if (pd.isShowing()) {
					pd.setMessage("更新设备信息");
				}
			}
		});

		mGlobalVariable.getmRequestWithToken().gettoken(new GetTokenCallback() {

			@Override
			public void onGetOK(final String token, final int timeout) {
				Map<String, Object> jsmap = new HashMap<String, Object>();
				jsmap.put("device_num", "1");

				Map<String, String> devicelistmap = new HashMap<String, String>();
				devicelistmap.put("id", deviceid);
				devicelistmap.put("mac", wxmac);
				devicelistmap.put("connect_protocol", "3");
				devicelistmap.put("auth_key", crypt_check.isChecked() ? cryptkey_edit.getText().toString() : "");
				devicelistmap.put("close_strategy", connectoutapp_check.isChecked() ? "2" : "1");
				devicelistmap.put("conn_strategy", "1");
				devicelistmap.put("crypt_method", crypt_check.isChecked() ? "1" : "0");
				devicelistmap.put("auth_ver", "0");
				devicelistmap.put("manu_mac_pos", "-1");
				devicelistmap.put("ser_mac_pos", "-2");
				devicelistmap.put("ble_simple_protocol", "0");

				jsmap.put("device_list", new Map[] { devicelistmap });
				jsmap.put("op_type", "1");
				jsmap.put("product_id", mGlobalVariable.getMixedvalues().getProductid());

				JSONObject js = new JSONObject(jsmap);
				System.out.println("发送结构->" + js.toString());

				String url = HTTPURL.REFRESHDEVICE_URL + "?access_token=" + token;
				System.out.println("url->" + url);

				JsonObjectRequest reflashdevice = new JsonObjectRequest(url, js, new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						System.out.println("reflashdevice onResponse->"+arg0.toString());
						try {
							JSONArray resp_array = arg0.getJSONArray("resp");
							JSONObject resp = resp_array.getJSONObject(0);
							int errcode = resp.getInt("errcode");
							if(errcode != 0){
								final String erromsg = resp.getString("errmsg");
								handl.post(new Runnable() {

									@Override
									public void run() {
										if (pd.isShowing()) {
											Toast.makeText(getApplicationContext(), "更新设备失败->" + erromsg,
													Toast.LENGTH_LONG).show();
											pd.dismiss();
										}
									}
								});
								System.out.println("获取错误->" + resp.getString("errmsg"));
								return;
							}
							
							handl.post(new Runnable() {

								@Override
								public void run() {
									if (pd.isShowing()) {
										pd.dismiss();
									}
								}
							});
							
						} catch (JSONException e) {
							e.printStackTrace();
							handl.post(new Runnable() {

								@Override
								public void run() {
									if (pd.isShowing()) {
										Toast.makeText(getApplicationContext(), "更新设备失败->参数错误",
												Toast.LENGTH_LONG).show();
										pd.dismiss();
									}
								}
							});
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						handl.post(new Runnable() {

							@Override
							public void run() {
								if (pd.isShowing()) {
									Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
									pd.dismiss();
								}
							}
						});
						System.out.println("onErrorResponse->" + arg0.toString());
					}
				});
				mGlobalVariable.getmRequestWithToken().addRequest(reflashdevice);
			}

			@Override
			public void onGetFail(ErroCode erro) {
				System.out.println("reflashInf onGetFail");
			}
		});
	}

}
